package com.bwie.service.Impl;

import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bwie.poi.ImageUtils;
import com.bwie.poi.StringUtils;
import com.bwie.utils.MD5Utils;
import com.bwie.utils.R;
import com.bwie.vo.LoginFromVo;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.List;
import java.util.concurrent.TimeUnit;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bwie.pojo.User;
import com.bwie.mapper.UserMapper;
import com.bwie.service.UserService;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService{
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Override
    public R login(LoginFromVo loginFromVo) {
        User user = userMapper.selectOne(
                new QueryWrapper<User>().lambda().eq(User::getUserName, loginFromVo.getUserName())
                        .or().eq(User::getUserEmail,loginFromVo.getUserName())
        );
        if(!user.getUserEmail().matches("^\\w+([-+.']\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$")){
            return R.ERROR(500,"邮箱格式不正确");
        }
        if(ObjectUtils.isEmpty(user)){
            return R.ERROR(500,"用户-邮箱未注册");
        }
        String encrypt = MD5Utils.encrypt(loginFromVo.getPassword());
        System.out.println("加密密码:"+encrypt);
        System.out.println("明文密码:"+loginFromVo.getPassword());
        if(!MD5Utils.encrypt(loginFromVo.getPassword()).equals(user.getPassword())){
            return R.ERROR(500,"密码错误");
        }
        String token = Jwts.builder().signWith(SignatureAlgorithm.HS256, "123456").
                claim("id", user.getId()).compact();
        String tokenKey =  "token-"+user.getId();
        user.setToken(token);
        redisTemplate.opsForValue().set(tokenKey,token,20, TimeUnit.MINUTES);
        return R.OK(user);
    }
}
